import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = () => {
  return {
    token: getToken() || null,
    userInfo: {}
  }
}
const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 设置用户信息
  setUserInfo(state, UserInfo) {
    state.userInfo = UserInfo
  },
  // 退出清空token
  removeToken(state) {
    state.token = null
    // 清空token 本地存储
    removeToken()
  },
  // 清空用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async login(context, data) {
    const res = await reqLogin(data)
    // console.log(res, '00000000')
    context.commit('setToken', res.data)
    // return res
  },
  // 用户信息
  async userInfo(context) {
    // 获取用户基本信息
    const { data: res1 } = await reqGetUserInfo()
    // console.log(res1.userId)
    // 获取员工基本信息
    const { data: res2 } = await reqGetUserDetailById(res1.userId)
    // console.log(res2)
    const res = { ...res1, ...res2 }
    // console.log(res)
    context.commit('setUserInfo', res)
  },
  // 退出清空集体操作
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
